<template>
  <div class="user-manage-container card">
    <div class="header-row">
      <div class="title-area">
        <h2 class="page-title">员工管理</h2>
        <p class="page-sub">按姓名搜索、选择并管理员工信息</p>
      </div>

      <div class="ops-area">
        <div class="search-container">
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="请输入关键词搜索 (姓名)"
            @keyup.enter="handleSearch"
          />
          <button class="btn btn-primary" @click="handleSearch">搜索</button>
        </div>

        <div class="action-buttons">
          <button class="btn btn-danger" @click="handleDelete" :disabled="!selectedUser">删除</button>
        </div>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <table class="user-table">
        <thead>
          <tr>
            <th>员工ID</th>
            <th>姓名</th>
            <th>用户名</th>
            <th>部门</th>
            <th>职位</th>
            <th>状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in filteredList" :key="user.empId"
              :class="{ selected: selectedUser && selectedUser.empId === user.empId }"
              @click="selectUser(user)">
            <td>{{ user.empId }}</td>
            <td>{{ user.empName }}</td>
            <td>{{ user.loginId }}</td>
            <td>{{ getDeptName(user.deptId) }}</td>
            <td>{{ user.position }}</td>
            <td>{{ getUserStatus(user.resignDate) }}</td>
          </tr>
          <tr v-if="filteredList.length === 0 && !loading">
            <td colspan="6" class="empty-text">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">加载中...</div>

    <!-- 分页组件 -->
    <div class="pagination" v-if="filteredList.length > 0">
      <button 
        class="page-btn" 
        @click="changePage(currentPage - 1)" 
        :disabled="currentPage <= 1 || loading"
      >
        上一页
      </button>
      <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
      <button 
        class="page-btn" 
        @click="changePage(currentPage + 1)" 
        :disabled="currentPage >= totalPages || loading"
      >
        下一页
      </button>
      <span class="total-info">共 {{ total }} 条记录</span>
    </div>

    <!-- 新增员工弹窗 -->
    <AddEmployeeDialog 
      :visible="showAddDialog"
      @close="showAddDialog = false"
      @submit="handleAddEmployee"
    />
  </div>
</template>

<script>
import { getUserList, addEmployee, deleteEmployee } from '@/api/userManager'
import AddEmployeeDialog from './AddEmployeeDialog.vue'  // 导入弹窗组件

export default {
  name: 'EmployeeManage',
  components: {
    AddEmployeeDialog
  },
  data() {
    return {
      userList: [], // 员工列表数据
      filteredList: [], // 过滤后的数据
      selectedUser: null, // 添加选中用户的变量
      loading: false, // 加载状态
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 总记录数
      totalPages: 0, // 总页数
      searchKeyword: '', // 搜索关键词
      showAddDialog: false  // 控制新增弹窗显示
    }
  },
  created() {
    // 页面初始化时加载数据
    this.loadUserList()
  },
  methods: {
    /**
     * 选择用户
     * @param {Object} user - 选中的用户
     */
    selectUser(user) {
      this.selectedUser = user;
    },
    /**
     * 处理新增员工提交
     * @param {Object} employee - 员工信息
     */
    async handleAddEmployee(employee) {
      try {
        // 调用新增接口
        const response = await addEmployee(employee)
        
        // 新增成功后提示并刷新列表
        alert(response.message || '新增员工成功')
        this.showAddDialog = false  // 关闭弹窗
        this.loadUserList()  // 重新加载列表数据
      } catch (error) {
        // 失败提示
        alert(error.message || '新增员工失败，请重试')
      }
    },
    /**
     * 加载用户列表数据
     */
    async loadUserList() {
      this.loading = true
      this.selectedUser = null // 清除选中状态
      try {
        const response = await getUserList({
          page: this.currentPage,
          size: this.pageSize,
          keyword: this.searchKeyword || undefined // 如果有搜索关键词则传递
        })
        
        
        // 处理接口返回数据
        if (response.data) {
          this.userList = response.data.records || []
          this.total = response.data.total || 0
          this.totalPages = response.data.pages || 0
          this.currentPage = response.data.current || 1
          // 在数据加载完成后执行过滤
          this.filterData()
        }
      } catch (error) {
        console.error('加载用户列表失败:', error)
        this.userList = []
        this.total = 0
        this.totalPages = 0
      } finally {
        this.loading = false
      }
    },

    /**
     * 切换页码
     * @param {number} page - 目标页码
     */
    changePage(page) {
      if (page < 1 || page > this.totalPages) return
      this.currentPage = page
      this.loadUserList()
    },

    /**
     * 处理搜索
     */
    handleSearch() {
      // 重置页码为第一页
      this.currentPage = 1
      this.loadUserList()
      
      // 这里可以根据实际搜索需求调整，当前接口文档未提供搜索参数，暂用原有接口
      
      // 添加调试信息
      setTimeout(() => {
        console.log('当前员工列表:', this.userList)
      }, 100)
    },

    /**
     * 处理修改操作
     */
    handleEdit() {
      if (!this.selectedUser) {
        alert('请选择要修改的员工')
        return
      }
      alert(`修改员工 ${this.selectedUser.empName} 功能待实现`)
    },

    /**
     * 处理删除操作
     */
    async handleDelete() {
      if (!this.selectedUser) {
        alert('请选择要删除的员工')
        return
      }
      
      if (confirm(`确定要删除员工 ${this.selectedUser.empName} 吗？`)) {
        try {
          const response = await deleteEmployee(this.selectedUser.empId)
          alert(response.message || '删除成功')
          this.loadUserList() // 重新加载列表
        } catch (error) {
          alert(error.message || '删除失败，请重试')
        }
      }
    },

    /**
     * 处理新增操作
     */
    handleAdd() {
      this.showAddDialog = true
    },
    /**
     * 根据搜索关键词过滤数据
     */
    filterData() {
      if (!this.searchKeyword) {
        // 如果没有搜索关键词，显示所有数据
        this.filteredList = this.userList
        return
      }
      
      // 根据姓名进行模糊匹配
      this.filteredList = this.userList.filter(user => 
        user.empName.includes(this.searchKeyword)
      )
    },

    /**
     * 根据部门ID获取部门名称
     * 实际项目中可能需要从部门列表中匹配
     */
    getDeptName(deptId) {
      // 这里仅做示例，实际项目中应从部门数据中获取
      const deptMap = {
        1: '技术部',
        2: '市场部',
        3: '人事部'
      }
      return deptMap[deptId] || '未知部门'
    },

    /**
     * 根据离职日期判断用户状态
     */
    getUserStatus(resignDate) {
      return resignDate ? '已离职' : '在职'
    }
  }
}
</script>

<style scoped>
/* 蓝色主题变量（组件级） */
:root {
  --primary: #1f6feb;
  --primary-600: #165fc1;
  --muted: #6b7280;
  --card-bg: #ffffff;
  --bg: #f5f8ff;
  --radius: 10px;
}

.user-manage-container{
  padding: 18px;
  max-width: 1200px;
  margin: 18px auto;
  background: var(--bg);
  border-radius: var(--radius);
}

.card{background:var(--card-bg);padding:18px;border-radius:8px;box-shadow:0 6px 18px rgba(31,111,234,0.06)}

.header-row{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;margin-bottom:14px}
.title-area .page-title{margin:0;color:var(--primary);font-size:20px}
.page-sub{margin:4px 0 0;color:var(--muted);font-size:13px}

.ops-area{display:flex;align-items:center;gap:12px}
.search-container{display:flex;align-items:center;gap:8px}
.search-container input{width:360px;padding:8px 12px;border:1px solid rgba(31,111,234,0.18);border-radius:8px;outline:none}
.search-container input:focus{box-shadow:0 0 0 4px rgba(31,111,234,0.08);border-color:var(--primary)}

.btn{padding:8px 14px;border-radius:8px;border:none;cursor:pointer;font-weight:600}
.btn-primary{background:linear-gradient(90deg,var(--primary),var(--primary-600));color:#fff}
.btn-outline{background:#fff;border:1px solid rgba(31,111,234,0.12);color:var(--primary)}
.btn-edit{background:linear-gradient(90deg,#3b82f6,#2563eb);color:#fff}
.btn-danger{background:linear-gradient(90deg,#ef4444,#dc2626);color:#fff}
.btn:disabled{opacity:0.6;cursor:not-allowed}

.table-container{margin-top:8px;border-radius:8px;overflow:hidden;border:1px solid rgba(15,23,42,0.04)}
.user-table{width:100%;border-collapse:collapse}
.user-table th,.user-table td{padding:12px 14px;text-align:left;border-bottom:1px solid #f1f5f9}
.user-table thead th{background:linear-gradient(90deg,rgba(31,111,234,0.06),rgba(31,111,234,0.02));color:var(--primary);font-weight:700}
.user-table tbody tr{transition:background 0.12s}
.user-table tbody tr:hover{background:rgba(31,111,234,0.03);cursor:pointer}
.user-table tr.selected{background:linear-gradient(90deg,rgba(31,111,234,0.08),rgba(31,111,234,0.03))}

.empty-text{text-align:center;padding:28px;color:#9aa4bf}
.loading{text-align:center;padding:20px;color:var(--muted)}

.pagination{display:flex;align-items:center;gap:12px;justify-content:center;margin-top:16px}
.page-btn{padding:6px 12px;border-radius:8px;border:1px solid rgba(15,23,42,0.06);background:#fff}
.page-info{color:var(--muted)}
.total-info{margin-left:12px;color:var(--muted)}

.action-buttons{display:flex;gap:8px}

/* responsive */
@media (max-width:900px){
  .search-container input{width:200px}
  .header-row{flex-direction:column;align-items:stretch}
}

</style>